//
//  MyNavigationBar.m
//  Demo
//
//  Created by Visitor on 15/12/7.
//  Copyright © 2015年 Visitor. All rights reserved.
//

#import "MyNavigationBar.h"
#define WH 25
@implementation MyNavigationBar

- (instancetype)init

{
    self = [super init];
    if (self) {
        self.frame = CGRectMake(0, 20, [[UIScreen mainScreen] bounds].size.width, 44);
    }
    return self;
}

- (void)setNavigationBarWithBgImageName:(NSString *)bgImageName andTitle:(NSString *)title andTitleView:(UIView *)titleView andLeftItems:(NSArray *)leftItems andRightItems:(NSArray *)rightItems
{
    [self createBgImageViewWithImageName:bgImageName];
    [self createTitleWithTitle:title];
    [self createTitleViewWithView:titleView];
    
    CGFloat x = 0.f;
    for(MyNavigationItem *item in leftItems)
    {
        x = [self createItemWithItem:item andIsLeft:YES andX:x];
    }
    
    x = self.frame.size.width;
    for(MyNavigationItem *item in rightItems)
    {
        x = [self createItemWithItem:item andIsLeft:NO andX:x];
    }
}

// 创建背景图
- (void)createBgImageViewWithImageName:(NSString *)imageName
{
    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:imageName]];
    imageView.frame = self.bounds;
    [self addSubview:imageView];
}

// 创建标题
- (void)createTitleWithTitle:(NSString *)title
{
    UILabel *label = [[UILabel alloc] init];
    label.tag = 2002;
    label.frame = self.bounds;
    label.text = title;
    label.textColor = [UIColor blackColor];
    label.textAlignment = NSTextAlignmentCenter;
    label.font = [UIFont systemFontOfSize:14];
    [self addSubview:label];
}

// 创建标题视图
- (void)createTitleViewWithView:(UIView *)view
{
    view.center = CGPointMake(self.center.x, self.frame.size.height/2);
    [self addSubview:view];
}

// 创建按钮
- (CGFloat)createItemWithItem:(MyNavigationItem *)item andIsLeft:(BOOL)isLeft andX:(CGFloat)x
{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    UIImage *image = [UIImage imageNamed:item.itemImage];

    UIImage *selectImage = [UIImage imageNamed:item.itemHighlightImage];
    
    //image.size.width
    btn.frame = isLeft?CGRectMake(x+10, (self.frame.size.height-WH)/2, WH, WH):CGRectMake(x-10-WH, (self.frame.size.height-WH)/2, WH, WH);
    [btn setBackgroundImage:image forState:UIControlStateNormal];
    [btn setBackgroundImage:selectImage forState:UIControlStateHighlighted];
    btn.tag = item.itemTag;
    [btn addTarget:item.classObject action:item.sel forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:btn];
    
    return isLeft?CGRectGetMaxX(btn.frame):btn.frame.origin.x;
    

}

- (void)setMyNavigationBarTitleSize:(int)sizeNumber
{
    ((UILabel *)[self viewWithTag:2002]).font = [UIFont systemFontOfSize:sizeNumber];
}



/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
